<template>
  <div class="heard">
    <div class="content">
      <div class="logo">
        <!-- <router-link to='/' target="_blank">
          <img src="../assets/static/logo.png" />
        </router-link> -->
        <img src="../assets/static/logo.png" />
      </div>
      <div class="right-header">
        <el-autocomplete class="uni-input" :trigger-on-focus="false" v-model="searchInput" :fetch-suggestions="querySearch" placeholder="输入搜索店铺" @input="searchInput = searchInput.replace(/\s*/g,'')" @select="handleInputSelect">
        </el-autocomplete>
        <span class="search"></span>
      </div>
      <div class="right-header">
        <div class="right-header-item"><span class="phone"></span>手机端下载</div>
        <div class="right-header-item">
          <router-link tag="a" target="_blank" :to="{path:'./ground'}">了解我们</router-link><span class="info"></span>
        </div>
        <div class="right-header-item">|</div>
        <div class="right-header-item" @click="toggle()" v-if="!userInfo.userInfo">玩家登录</div>
        <div class="right-header-item-list" v-if="userInfo.userInfo">
          <router-link tag="a" target="_blank" :to="{path:'./my'}">
            <span class="logto">
              <img src="../assets/static/t-14.png" />
              <!-- {{userInfo.userInfo.nickName}} -->
              <router-link tag="a" target="_blank" :to="{path:'./my'}">个人中心</router-link>
            </span>
          </router-link>
          <span @click="logout()" class="logout">退出</span>
          <!-- <div class="dropdownmenu">
            <div class="logout">
              <router-link tag="a" target="_blank" :to="{path:'./my'}">个人中心</router-link>
            </div>
            <div @click="logout()" class="logout">退出</div>
          </div> -->
        </div>
        <div class="right-header-item" v-if="!userInfo.userInfo">
          <a target="_black" href="/admin">商家登录</a>
        </div>
      </div>
      <!-- 注册登录 -->

      <el-dialog width="360px" @open="opened" :destroy-on-close="true" :close-on-click-modal="false" :show-close="false" :visible.sync="uniPopup">

        <!-- 登录 -->
        <div class="login" v-show="is_login_register">
          <div class="close" @click="close">×</div>
          <!-- <div :class="!is_scan_pc?'login-wx-user':'login-pc-user'" @click="BindLoginUser">
            <span v-if="!is_scan_pc" class="saoma">微信扫码登录</span>
          </div> -->
          <div :class="!is_scan_pc?'login-wx-user':'login-pc-user'"></div>
          <div v-show="is_scan_pc" class="is_scan_pc">
            <div class="is_bing_phone" v-show="is_bing_phone">

              <div ref="weixinLogin" class="weixinLogin WeChatQr"></div>
              <div class="text">微信扫码登录</div>
            </div>

            <div v-show="!is_bing_phone">
              <h1 class="bingphone">绑定手机号</h1>
              <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
                <el-form-item prop="mobile">
                  <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                  <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
                  <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">确定</el-button>
            </div>

          </div>
          <!-- <div v-show="!is_scan_pc" class="is_scan_pc">
            <div class="login-title">
              <span @click="bindSms(true)" :class="is_sms_password?'atv':''">短信登录</span>
              <span @click="bindSms(false)" :class="!is_sms_password?'atv':''">密码登录</span>
            </div>

            <div v-if="is_sms_password">
              <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
                <el-form-item prop="mobile">
                  <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                  <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
                  <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
            </div>

            <div v-if="!is_sms_password">
              <el-form ref="formloginUser" :model="formloginUser" :rules="rulesUser">
                <el-form-item prop="username">
                  <el-input v-model="formloginUser.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="formloginUser.password" placeholder="请输入密码" @keyup.enter.native="loginUserSubmit" />
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" @click="loginUserSubmit">登录</el-button>
              <div class="agreement">
                <span>登录或注册代表您已阅读并接受</span>
                <router-link to='/'>《用户协议》</router-link>

                <router-link to='/'>《隐私政策》</router-link>
              </div>
              <div class="click-register">
                没有账号？
                <span @click="userLogin()">点击注册</span>
              </div>
            </div>
          </div> -->

        </div>
        <!-- 注册 -->
        <!-- <div class="login" v-show="!is_login_register">
          <div class="close" @click="close">×</div>
          <div class="login-title-red">注册账户</div>
          <el-form ref="form" :model="formData" :rules="rules">
            <el-form-item prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="formData.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input class="input" style="width:58%" v-model="formData.code" placeholder="手机验证码" />
              <div class="codephone" @click="getRegisterCode" v-if='registerisCodeShow'>{{registercodespan}}</div>
              <div class="codephone del" v-if='!registerisCodeShow'>{{registercodespan}}</div>
            </el-form-item>

          </el-form>
          <el-button class="userLogin" :loading="loading" @click="submit">注册</el-button>
          <div class="agreement">
            <span>登录或注册代表您已阅读并接受</span>
            <router-link to='/'>《用户协议》</router-link>
            <router-link to='/'>《隐私政策》</router-link>
          </div>
          <div class="click-register">
            <span @click="userLogin()">点击登录</span>
          </div>
        </div> -->
      </el-dialog>

    </div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import axios from 'axios'
export default {
  data () {
    return {
      qrUrlTime: null,
      qrUrl: 'https://api.fengwg.com/geem2/oauth2/authorize?state=',
      codUrl: 'https://api.fengwg.com/geem2/oauth2/querycode?state=',
      codUrlTime: null,
      searchInput: '',
      uniPopup: false,
      userInfo: '',
      time: null,
      registercodespan: '获取验证码',
      registerTime: null,
      registerisCodeShow: true,
      codespan: '获取验证码',
      isCodeShow: true,
      is_bing_phone: true, // 微信登录绑定手机
      is_login_register: true, // 登录或注册
      is_scan_pc: true, // 扫码或账号登录
      is_sms_password: true, // 短信登录或密码登录
      loading: false,
      formloginPone: {
        // 手机登录数据
        mobile: '',
        code: '',
        wxopenid: '',
        usertype: 0
      },

      formloginUser: {
        // 用户名登录数据
        username: '',
        password: ''
      },

      formData: {
        // 注册数据
        username: '',
        password: '',
        mobile: '',
        code: ''
      },
      rulesUser: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少 6个字符'
          }
        ]
      },
      rulesPhone: {
        // 数据校验
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少 4 个字符'
          }
        ]
      },
      rules: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少6 个字符'
          }
        ],

        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少4个字符'
          }
        ]
      }
    }
  },
  watch: {},
  computed: {},
  mounted () {
    const u = localStorage.getItem('storage_key')
    if (u) {
      this.userInfo = JSON.parse(u)
    }
  },

  methods: {
    handleInputSelect (e) {
      let routeData = this.$router.resolve({
        path: './detail',
        query: { id: e.id }
      })
      window.open(routeData.href, '_blank')
    },
    querySearch (queryString, cb) {
      if (queryString != '') {
        var restaurants = []
        var results
        this.$apis.shopList({ name: queryString }).then(res => {
          res.data.data.map(item => {
            restaurants.push({
              id: item.id,
              value: item.gameName
            })
          })
          results = queryString
            ? restaurants.filter(this.createStateFilter(queryString))
            : restaurants
          cb(results)
        })
      }
    },
    createStateFilter (queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },

    getLoginCode () {
      // 获取登录验证码

      this.$refs.formloginPone.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.time)
          let numberTime = 60
          this.isCodeShow = false
          this.time = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.time)
              this.codespan = '获取验证码'
              this.isCodeShow = true
              return
            }
            this.codespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formloginPone.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    getRegisterCode () {
      // 获取注册验证码
      this.$refs.form.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.registerTime)
          let numberTime = 60
          this.registerisCodeShow = false
          this.registerTime = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.registerTime)
              this.registercodespan = '获取验证码'
              this.registerisCodeShow = true
              return
            }
            this.registercodespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formData.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    submit () {
      // 注册
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .register({
              code: this.formData.code,
              mobile: this.formData.mobile,
              password: this.formData.password,
              username: this.formData.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('注册成功')
                this.userInfo = res.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },

    randomString (len) {
      let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      let maxPos = chars.length
      let character = ''
      for (let i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return character + new Date().getTime()
    },

    opened () {
      this.$nextTick(() => {
        this.pollQrCode()
      })
    },
    creatQrCode (url) {
      var element = this.$refs.weixinLogin
      element.innerHTML = ''
      var qrcode = new QRCode(element, {
        text: url, // 需要转换为二维码的内容
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    pollQrCode () {
      var cod = this.randomString(6)
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
      this.creatQrCode(this.qrUrl + cod)
      let self = this
      this.qrUrlTime = setTimeout(function () {
        self.pollQrCode()
      }, 1000 * 60)
      this.codUrlTime = setInterval(function () {
        axios.get(self.codUrl + cod + '&timestamp=' + Date.now()).then(res => {
          if (res.data.data.code != '') {
            clearTimeout(self.qrUrlTime)
            clearInterval(self.codUrlTime)
            self.loginByScanWeixin(res.data.data.code)
          }
        })
      }, 1000)
    },
    loginByScanWeixin (e) {
      // 微信扫码登录
      this.$apis
        .loginByScanWeixin({
          code: e
        })
        .then(res => {
          if (res.data.errno == 0) {
            const data = res.data.data
            if (data.token) {
              this.$message.success('登录成功')
              this.userInfo = data
              this.init(data)
            } else {
              this.formloginPone.wxopenid = data.openId
              this.is_bing_phone = false
            }
          } else {
            this.$message.error(res.data.errmsg)
          }
        })
    },
    loginPhoneSubmit () {
      // 手机登录
      this.$refs.formloginPone.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis.loginbymobile(this.formloginPone).then(res => {
            this.loading = false
            if (res.data.errno == 0) {
              this.$message.success('登录成功')
              this.userInfo = res.data.data
              this.init(res.data.data)
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
        }
      })
    },
    loginUserSubmit () {
      // 用户名登录

      this.$refs.formloginUser.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .login({
              password: this.formloginUser.password,
              username: this.formloginUser.username,
              usertype: 0
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('登录成功')
                this.userInfo = res.data.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    logout () {
      // 退出
      this.$apis.logout().then(res => {
        if (res.data.errno == 0) {
        }
        this.userInfo = ''
        localStorage.removeItem('storage_key')
        localStorage.removeItem('token')
        this.$store.commit('setUserInfo', '')
        this.$router
          .replace({ path: './' })
          .then()
          .catch(err => {
            // console.log(err)
          })
      })
    },

    toggle () {
      this.uniPopup = true
    },
    close () {
      this.uniPopup = false
      this.uniPopup = false
      this.is_scan_pc = true
      this.is_bing_phone = true
      this.formloginPone.wxopenid = ''
      this.formloginPone.mobile = ''
      this.formloginPone.code = ''
      this.formloginUser.username = ''
      this.formloginUser.password = ''
      this.formData.username = ''
      this.formData.password = ''
      this.formData.mobile = ''
      this.formData.code = ''
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
    },
    init (e) {
      this.close()
      localStorage.setItem('token', e.token)
      this.$store.commit('setUserInfo', e)
      localStorage.setItem('storage_key', JSON.stringify(e))
    },
    userLogin () {
      this.is_login_register = !this.is_login_register
      this.$refs.form.clearValidate()
    },
    BindLoginUser () {
      if (this.is_scan_pc) {
        this.is_scan_pc = false
        clearTimeout(this.qrUrlTime)
        clearInterval(this.codUrlTime)
      } else {
        this.pollQrCode()
        this.is_scan_pc = true
      }
    },
    bindSms (e) {
      if (this.is_sms_password == e) {
        return
      }
      if (e) {
        this.$refs.formloginUser.clearValidate()
      } else {
        this.$refs.formloginPone.clearValidate()
      }

      this.is_sms_password = e
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog__header {
  padding: 0px;
}
/deep/ .el-dialog__body {
  padding: 0px 20px;
}
.content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.logo {
  //   display: flex;
  //   flex-direction: row;
  //   align-items: center;
  //   flex: 1;
}

.logo img {
  max-height: 46px;
  width: 160px;
}

.logo span {
  margin-left: 16px;
}

.phone {
  background: url("../assets/static/t-02.png") no-repeat left center;
  background-size: 18px 22px;
  display: inline-block;
  width: 18px;
  height: 22px;
  vertical-align: sub;
  margin-right: 10px;
}
.info {
  background: url("../assets/static/t-04.png") no-repeat left center;
  background-size: 9px 6px;
  display: inline-block;
  width: 9px;
  height: 6px;
  vertical-align: middle;
  margin-left: 10px;
}

.uni-input {
  width: 437px;
  height: 40px;
  box-sizing: border-box;
  background: #f3f4f5;
  border: 1px solid #f3f4f5;
  border-radius: 22px;
  padding: 0px 20px;
}
.search {
  background: url("../assets/static/t-03.png") no-repeat left center;
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 40px;
  margin-left: 10px;
}

.forget-password {
  span-align: right;
  color: #3377aa;
  cursor: pointer;
}
.forget-password:hover {
  color: #da2740;
}
.userLogin {
  background: #da2740;
  color: #fff;
  margin: 15px 0;
  width: 100%;
}
uni-navigator {
  display: inline;
  color: #3377aa;
}
.click-register {
  text-align: right;
  margin: 25px 0 10px;
  span {
    color: #3377aa;
    cursor: pointer;
  }
}

.heard {
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 4px 19px 1px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: row;
  ustify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  margin-bottom: 15px;
}

.is_bing_phone {
  text-align: center;
  overflow: hidden;
  .text {
    font-size: 22px;
  }
  .WeChatQr {
    padding: 20px 0px;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
}
.is_scan_pc {
  overflow: hidden;
}
</style>
